package com.jackrain.nea.omslocal.Dao;/**
 * Created by Administrator on 2017/4/5.
 */

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.omslocal.service.LocalLogService;
import com.jackrain.nea.omslocal.service.SendMqServies;
import com.jackrain.nea.omslocal.util.RegexDateUtil;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;

/**
 * Description:
 * Created with IntelliJ IDEA.
 * User: xyc
 */
@Component
@Slf4j
public class VopFullQtyDao {

    @Autowired
    private RegexDateUtil regexDate;
    private FastDateFormat fastformat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private LocalLogService localLogService;


    @Autowired
    private SendMqServies sendMq;


    /**
     * 全量库存同步
     *
     * @param fullQtyArr
     * @param topic
     */
    public void fullQtyStart(JSONArray fullQtyArr, String msgkey, String topic, String tag) throws Exception {

        // 遍历消息体
        for (Object obj : fullQtyArr) {

            JSONObject tempObj = null;
            try {
                // 循环遍历获取会员数据
                tempObj = JSONObject.parseObject(obj.toString(), Feature.OrderedField);
                //获取批次
                String batchNo =  tempObj.getString("BatchNo");
                //平台
                Integer platForm = tempObj.getInteger("PlatForm");
                //消息数据
                JSONArray data = (JSONArray) tempObj.get("Data");
                for (int i = 0; i < data.size(); i++) {
                    int status = 0;
                    JSONObject datadetail = data.getJSONObject(i);
                    String extSkuID = datadetail.getString("ExtSkuID");
                    long shopStock = datadetail.getLong("Quantity");
                    boolean isSuccess = false;
                    try {
                        isSuccess = datadetail.getBoolean("ISSUCCESS");
                    } catch (NullPointerException e) {
                        //  空指针, 没有isSuccess 参数,默认同步失败
                        isSuccess =false;
                    }

                    if(isSuccess){
                        status = 1;
                    }else {
                        status = 2;
                    }
                    String msg = datadetail.getString("MSG");

                    // 更新主表数据
                    update(batchNo, platForm, extSkuID, shopStock, status, msg);
                    // 根据sku更新t_iessku表safenum值
                    if(platForm == 19 && isSuccess == true){
                        //库存占用
                        Integer current_hold = datadetail.getInteger("CURRENT_HOLD");
                        String sku = datadetail.getString("Sku");
                        String sql = "update T_IESSKU set SAFENUM = ? where SKU = ?";
                        if(current_hold >= 0){
                            System.out.println("更新安全库存：sku:" + sku + " current_hold:" + current_hold);
                            QueryEngine.getInstance().executeUpdate(sql, new Object[]{current_hold, sku});
                        }
                    }

                }

            } catch (Exception e) {
                log.error("msgkey=>"+ msgkey + " topic=>"+ topic + " tag=>"+ tag);
            }

        }

    }

    /**
     * 检查extSkuID是否是处理成功数据
     * @param extSkuID
     * @param errData
     * @return
     */
    private Boolean checkExtShuId(String extSkuID, String errData) {
        boolean isTrue = false;

        if(errData.indexOf(extSkuID)!=-1){
            isTrue = true;
        }else{
            isTrue = false;
        }

        return isTrue;
    }

    @Transactional
    public void update(String batchNo, Integer platForm, String extSkuID, long shopStock, int status, String msg) throws Exception {
        // 根据BatchNo，PlatForm ，ExtSkuID修改t_iessynstockqueue中对应的同步数据的同步结果（ShopStock，SynStatus，msg）
        updateStock(batchNo, platForm, extSkuID, shopStock, status, msg);
        System.out.println("唯品会全量库存同步：batchNo:"+ batchNo + " platForm:" + platForm + " extSkuID:" + extSkuID +  " shopStock:" + shopStock + " status:" + status + " msg:" + msg);
    }


    /**
     * 更新主表
     * @param batchNo
     * @param platForm
     * @param extSkuID
     * @param shopStock
     * @throws SQLException
     * @throws ParseException
     */
    public void updateStock(String batchNo, Integer platForm, String extSkuID, long shopStock, int status, String msg) throws SQLException, ParseException {
        Date modifiedDate = new Date(System.currentTimeMillis());
        String sql = "update T_IESSYNSTOCKQUEUE set SYNCNUM = "+shopStock+", SYNSTATUS = ?, ERRORMSG = ?, MODIFIEDDATE = ? where BATCHNO = ? and PLATFORM = ? and EXTSKUID = ?";
        if(status == 2){
            sql = "update T_IESSYNSTOCKQUEUE set SYNCNUM = 0, SYNSTATUS = ?, ERRORMSG = ?, MODIFIEDDATE = ? where BATCHNO = ? and PLATFORM = ? and EXTSKUID = ?";
        }

        QueryEngine.getInstance().executeUpdate(sql, new Object[]{status, msg, modifiedDate, batchNo, platForm, extSkuID});
    }

}
